package com.ruoyi.controller;

import com.alibaba.fastjson2.JSONObject;

import com.dingtalk.api.response.OapiUserGetuserinfoResponse;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.exception.BizException;
import com.ruoyi.service.DingService;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import com.ruoyi.utils.DingDingUtil;
import com.taobao.api.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;

/**
 * @Classname DingDing登陆验证
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/4/19 10:56
 * @Created by m元波
 */
@RestController
@RequestMapping("dd")
public class DingDingController {
    @Value("${azure.appkey}")
    private String appkey;
    @Value("${azure.appsecret}")
    private String appsecret;

    @Autowired
    SysUserServiceImpl sysUserService;
    @Autowired
    DingService dingService;
    /**
     * @param code 免登授权码
     * @return
     */
    @PostMapping("login")
    public AjaxResult ddLogin(@RequestParam @NotBlank String code) throws BizException, ApiException {
        //获取access_token
        String access_token = DingDingUtil.getAccessToken(appkey, appsecret);
        if (StringUtils.isBlank(access_token)) {
            return AjaxResult.error("登陆失败");
        }
        //查询用户钉钉id
        String dingId = DingDingUtil.getDingDingUserId(code, access_token);
        if (StringUtils.isBlank(dingId)){
            return AjaxResult.error("登场凭证获取失败");
        }
        String dingDingUserInfo = DingDingUtil.getDingDingUserInfo(dingId, access_token);
        JSONObject result = JSONObject.parseObject(dingDingUserInfo);
        System.out.println(result.get("result"));
        JSONObject ss = (JSONObject) result.get("result");
        String token = dingService.getToken(ss);
        if (StringUtils.isBlank(token)) {
            return AjaxResult.error("登陆失败");
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }
}

